#coding:utf8
#  
# Author: TooNTonG
# Created on 2010-9-16
#
from django.http import HttpResponse
from libs.protocol import xml2PyObj 
import urllib2
SERVICE = '58.68.150.204'

def _httpPost(func, data, isAssertOk = True, v = '2', http = 'HTTP'):
    url = '%s://%s/xsvr/%s/' % (http, SERVICE, func)
    xmlData = '''<?xml version="1.0"?><xLive>%s</xLive>''' %  data
    req = urllib2.Request(url, xmlData, headers = {'v':v, 'User-Agent':'toontong'})
    res = urllib2.urlopen(req).read()
    if isAssertOk:
        assert str(res).find('ok') != -1, (func, res, xmlData)
    return str(res)

def _call(func, token, **agr):
    data = '''<token>%s</token>''' % token
    for k, v in agr.iteritems():
        data += '''<%s>%s</%s>''' % (k, v, k)
    return _httpPost(func, data)


class Kuaipan(object):
    def login(self, email, password):
        agrs = {'user':email, 'password':password, 'deviceId':'TOON', 'clientName':'TOON', 'clientVersion':'0.1'}
        data = ''.join([ '''<%s>%s</%s>''' % (k, v, k) for k, v in agrs.iteritems()])
        return _httpPost('login', data)
        
kuaipaiApi = Kuaipan()

def login(request):
    email = request.GET.get('email')
    password = request.GET.get('password')
    return HttpResponse(xml2PyObj(kuaipaiApi.login(email, password)).__str__())
    